package servlet;

import bean.Article;
import bean.User;
import db.DbFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

@WebServlet("/user/publish.do")
public class PublishServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        InputStream inputStream = request.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String message = "";
        while ((line = bufferedReader.readLine()) != null) {
            message += line;
        }
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        Article article = new Article();
        article.setContent(message);
        article.setPublish(new Date());
        article.setOwner(currentUser.getId());

        DbFactory.getArticleDao().create(article);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(
                "{\"content\":\"" + article.getContent() + "\"," +
                        "\"publish\":\"" + article.getPublish() + "\"}"
        );

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
